package com.itheima.test;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;   
import com.fasterxml.jackson.databind.SerializerProvider;   
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;

import java.io.IOException;

@Data
public class UserDTO {
    private Long id;
    private String name;
    
    // 数据脱敏 - 手机号
    @JsonSerialize(using = PhoneSerializer.class)
    private String phone;
    
    // 数据脱敏 - 身份证号
    @JsonSerialize(using = IdCardSerializer.class)
    private String idCard;
    
    // 新增翻译字段 (非数据库字段)
    @JsonSerialize(using = GenderSerializer.class)
    private Integer gender;
    
    private String genderText; // 翻译后的文本
    
    // getters and setters   
}
   
// 手机号脱敏序列化器   
class PhoneSerializer extends JsonSerializer<String> {
    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) 
        throws IOException {
        if (value != null && value.length() > 7) {
            gen.writeString(value.substring(0, 3) + "****" + value.substring(7));
        } else {
            gen.writeString(value);
        }
    }   
}
   
// 身份证号脱敏序列化器   
class IdCardSerializer extends JsonSerializer<String> {
    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) 
        throws IOException {
        if (value != null && value.length() > 15) {
            gen.writeString(value.substring(0, 6) + "********" + value.substring(14));
        } else {
            gen.writeString(value);
        }
    }   
}
   
// 性别翻译序列化器   
class GenderSerializer extends JsonSerializer<Integer> {
    @Override
    public void serialize(Integer value, JsonGenerator gen, SerializerProvider serializers) 
        throws IOException {
        gen.writeNumber(value);
        String genderText = "";
        if (value == 1) {
            genderText = "男";
        }
        else if (value == 2) {
            genderText = "女";
        }
        else {
            genderText = "未知";
        }
        gen.writeStringField("genderText", genderText);
        gen.writeStringField("genderText", "1");
    }
}    
